<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h3>个人信息设置</h3>
        </div>
      </template>
      
      <div class="avatar-container">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="customUpload"
          accept=".jpg,.jpeg,.png"
        >
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="avatar-tip">点击更换头像</div>
      </div>

      <el-form :model="userInfo" :rules="rules" ref="formRef" label-width="100px" class="settings-form">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userInfo.nickname" placeholder="请输入昵称" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpdate" :loading="loading">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getUserInfo, updateUserInfo } from '@/api/user'
import { initOSSClient, validateFile } from '@/utils/oss'
import {uploadAvatar, uploadImg} from "@/api/user.js";
const userInfo = ref({
  username: '',
  nickname: '',
  avatar: ''
})

const loading = ref(false)
const formRef = ref(null)

// 表单验证规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在 2 到 20 个字符之间', trigger: 'blur' }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await getUserInfo()
    userInfo.value = data
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}

// 自定义上传方法
const customUpload = async ({ file }) => {
  try {
    console.log('开始上传文件:', {
      fileName: file.name,
      fileSize: (file.size / 1024 / 1024).toFixed(2) + 'MB',
      fileType: file.type
    })

    // 开始验证文件...
    console.log('开始验证文件...')
    await validateFile(file)
    console.log('文件验证通过')

    // 生成OSS存储路径
    const filePath = `avatars/wcw/${Date.now()}-${file.name}`
    console.log('OSS存储路径:', filePath)

    // 开始上传到OSS
    console.log('开始上传到OSS...')
    const fileUrl = await uploadAvatar(file, { path: filePath })

    // 更新用户头像
    userInfo.value.avatar = fileUrl
    await updateUserInfo(userInfo.value)
    ElMessage.success('头像更新成功')

  } catch (error) {
    console.error('头像上传失败:', {
      error: error.message,
      stack: error.stack
    })
    ElMessage.error('头像上传失败：' + error.message)
    throw error
  }
}

// 上传前校验
const beforeAvatarUpload = (file) => {
  console.log('上传前校验文件:', {
    fileName: file.name,
    fileSize: (file.size / 1024 / 1024).toFixed(2) + 'MB',
    fileType: file.type
  })
  
  try {
    validateFile(file, {
      maxSize: 2 * 1024 * 1024, // 2MB
      allowedTypes: ['image/jpeg', 'image/png']
    })
    console.log('文件校验通过')
    return true
  } catch (error) {
    console.error('文件校验失败:', error.message)
    ElMessage.error(error.message)
    return false
  }
}

// 更新用户信息
const handleUpdate = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await updateUserInfo(userInfo.value)
        ElMessage.success('更新成功')
      } catch (error) {
        ElMessage.error('更新失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 初始化OSS客户端
onMounted(() => {
  fetchUserInfo()
  initOSSClient()
})
</script>

<style scoped>
.settings-container {
  padding: 24px;
  max-width: 800px;
  margin: 0 auto;
}

.settings-card {
  background: var(--el-bg-color);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--el-text-color-primary);
}

.avatar-container {
  text-align: center;
  margin: 20px 0 30px;
}

.avatar-uploader {
  display: inline-block;
}

.avatar-uploader :deep(.el-upload) {
  border: 2px dashed var(--el-border-color);
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  text-align: center;
  line-height: 128px;
}

.avatar {
  width: 128px;
  height: 128px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-tip {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-top: 8px;
}

.settings-form {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.el-input {
  max-width: 300px;
}
</style> 